package com.example.orderservice.controller;

import com.example.orderservice.bean.Order;
import com.example.orderservice.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService service;

    @RequestMapping("/findall")
    public List<Order> findAll() { return service.findAll(); }

    @HystrixCommand(fallbackMethod = "findByIdFallback")
    @RequestMapping("/findbyid/{id}")
    public Order findById(@PathVariable Long id) throws Exception {
        Order order = service.findById(id);
        if (order == null) throw new Exception("Order not found");
        return order;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public int createOrder(@RequestBody Order order) {
        order.setStatus("NEW");
        return service.createOrder(order);
    }

    @RequestMapping(value = "/updateStatus", method = RequestMethod.PUT)
    public int updateStatus(@RequestParam Long id, @RequestParam String status) {
        return service.updateStatus(id, status);
    }

    public Order findByIdFallback(Long id) {
        Order order = new Order();
        order.setId(-1L);
        order.setStatus("Not found");
        return order;
    }
}